﻿using AutoMapper;
using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.ReadAPI.Applications.Commands.MeetingRooms;
using B.S.Meeting.ReadAPI.Dtos;
using MediatR;
using Microsoft.Data.SqlClient.Server;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;

namespace B.S.Meeting.ReadAPI.Applications.CommandHandlers.MeetingRooms
{
    public class GetRoomCommandHandler : IRequestHandler<GetRoomCommand, APIResult<APIPaging<List<RoomDto>>>>
    {
        IBaseRepository<MeetingRoom> mrRep;
        IMapper mapper;
        ILogger<GetRoomCommandHandler> logger;

        public GetRoomCommandHandler(IBaseRepository<MeetingRoom> mrRep, IMapper mapper, ILogger<GetRoomCommandHandler> logger)
        {
            this.mrRep = mrRep;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<APIResult<APIPaging<List<RoomDto>>>> Handle(GetRoomCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var list = mrRep.GetAll().Where(x=>x.IsDel == false);
                if(!string.IsNullOrEmpty(request.MeetingRoomName))
                {
                    list = list.Where(x => x.MeetingRoomName.Contains(request.MeetingRoomName));
                }
                int totalCount = list.Count();
                int totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
                list = list.OrderBy(x => x.MeetingRoomId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
                var rDto = mapper.Map<List<RoomDto>>(list);
                return new APIResult<APIPaging<List<RoomDto>>>
                {
                    Code=StatusEnumCode.Ok,
                    Message="获取会议室列表成功",
                    Data = new APIPaging<List<RoomDto>>
                    {
                        TotalCount = totalCount,
                        TotalPage = totalPage,
                        Data = rDto
                    }
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message, "获取会议室列表失败");
                throw;
            }
        }
    }
}
